package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.domain.R;
import com.itheima.domain.User;
import com.itheima.dto.LoginDto;
import com.itheima.service.UserService;
import com.itheima.ulits.SendSms;
import com.itheima.ulits.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    //获取验证码功能
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpServletRequest httpServletRequest) {

        //生成验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        System.out.println("生成验证码为:"+ code);
        //将生成的验证码发送给指定的手机
        SendSms.sendMsg(user.getPhone(), code + "");
        //再将验证码存到session中
        httpServletRequest.getSession().setAttribute(user.getPhone(), code + "");
        return R.success("验证码发送成功");
    }

    //验证码登录功能
    @PostMapping("/login")
    public R login(@RequestBody LoginDto loginDto, HttpServletRequest httpServletRequest) {
        //2). 从Session中获取到手机号对应的正确的验证码
        String code = (String) httpServletRequest.getSession().getAttribute(loginDto.getPhone());

        //2.1 校验一下code 如果为空
        if (null == code || code == "") {
            return R.error("请先获取验证码");
        }
        //3). 进行验证码的比对 , 如果比对失败, 直接返回错误信息
        if (!code.equals(loginDto.getCode())) {
            return R.error("验证码不匹配");
        }
        //4). 如果比对成功, 需要根据手机号查询当前用户, 如果用户不存在, 则自动注册一个新用户
        LambdaQueryWrapper<User> wapper = new LambdaQueryWrapper<>();
        wapper.eq(User::getPhone,loginDto.getPhone());
        User user = userService.getOne(wapper);

        if(user == null){ //代表用户不存在
            //注册一个用户
            user = new User();
            user.setPhone(loginDto.getPhone());
        }
        //4.1 插入数据库中
        userService.save(user);
        //5). 将登录用户的ID存储Session中
        httpServletRequest.getSession().setAttribute("user",user.getId());
        return R.success("登录成功");
    }

    //退出登录功能
    @PostMapping("/loginout")
    public R loginout(){
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute("user",null);
        return R.success("退出成功");
    }
}
